<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <!-- 日期搜索组件 -->
    <CommonDateSearch ref="searchRef" @search="handleSearch" @change="handleChange">
      <template #advanceBefore>
        <Button type="primary mr2" @click="handleExport" >导出</Button>
      </template>
    </CommonDateSearch>
    <div v-show="currentModel == 'table'" class="main-box">
      <div class="content-box2">
        <a-tabs v-model:activeKey="currentTab" @change="changeTabData">
          <a-tab-pane v-for="item in tabData" :key="item.itemName" :tab="item.itemName"></a-tab-pane>
          <template #rightExtra>
            <a-range-picker :getPopupContainer="(triggerNode) => triggerNode.parentNode" v-model:value="year2"
              format='YYYY-MM-DD' />
            <a-button type="primary" @click="updateList" :loading="exportLoading">同步</a-button>
          </template>
        </a-tabs>
      </div>
      <!-- 将表格和底部组件放在一个容器中，各占50% -->
      <div class="content-container">
        <div class="table-container">
          <a-card class="common-card" :title="`${currentBtn}的数据`">
            <BasicTable @register="registerTable" style="height:100%;overflow: auto;">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <TableAction :actions="createActions(record)" />
                </template>
              </template>
            </BasicTable>
          </a-card>
        </div>
        <div class="bottom-container">
          <ccssGasbottom ref="childRef" :searchInfo="searchInfo" @typeLoaded="typeLoaded" @reload-data="childReloadData"></ccssGasbottom>
        </div>
      </div>
    </div>
    <div v-if="currentModel != 'table'" class="main-box">
      <ccssGasCharts ref="csssGasChartsRef"></ccssGasCharts>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, nextTick } from 'vue';
import { DatePicker } from 'ant-design-vue';
import { PageWrapper } from '@/components/Page';
import CommonDateSearch from './CommonDateSearch.vue';
import Icon from '@/components/Icon/Icon.vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { cloneDeep, head } from 'lodash-es';
import TotalTable from './totalTable.vue';
import { selectCcssConsumptionData, cssConsumptionAddOrUpdate, exportCcssConsumptionData } from '@/api/common/chart';
import {
  getCcssplanNumDataSyn
} from '@/api/power/airConditioning/dailyUsage';
import { getDictListByCode } from '@/api/sys/dict';
import dayjs, { Dayjs } from 'dayjs';
import { useMessage } from '@/hooks/web/useMessage';
import Detail from './Detail.vue';
import { Button } from 'ant-design-vue';
import ccssGasbottom from './ccssGasComponents/ccssGasbottom.vue';
import ccssGasCharts from './ccssGasComponents/ccssGasCharts.vue';
import {
    downloadByData,
  } from '@/utils/file/download';
const chart = 'gas_tgm_consumption_chart';
const tabData = ref();
const currentTab = ref();
const dateList = reactive([]);
const currentEditKeyRef = ref('');
const dateMonthValue = ref(dayjs());
const currentBtn = ref('Arry');
const classifyId = ref('');
const year2 = ref<dayjs[]>([dayjs(), dayjs()]);
const exportLoading = ref(false);
const searchRef = ref();
// 定义响应式的 searchInfo 对象
const searchInfo = reactive({});
// 定义子组件引用
const childRef = ref();
const currentModel = ref('table')
const csssGasChartsRef = ref(null)
const classifyIdsObj:any = ref({
  ccssClassifyIds:[],
  gasClassifyIds:[]
})
const { createMessage: msg } = useMessage();
const dictCode = 'gas_ccss_consumption';

const [registerTable, { reload, setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: true,
  isCanResizeParent: true,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
  },

});

function createActions(record) {
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
        onClick: handleEdit.bind(null, record),
      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ];
}
const handleExport = async () => {
  const { data, headers } = await exportCcssConsumptionData({...searchInfo})
  let contentDisposition = decodeURIComponent(headers["content-disposition"])
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName)
}
const updateList = () => {
  console.log(123123123123);

  const [startTime, endTime] = year2.value;
  const formattedStart = startTime.format('YYYY-MM-DD');
  const formattedEnd = endTime.format('YYYY-MM-DD');
  getCcssplanNumDataSyn({ startDate: formattedStart, endDate: formattedEnd, planNum: "" });
  getData();
  handleSaveAndNotifyChild()
};

const handleCancel = (record) => {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
};

const handleEdit = (record) => {
  currentEditKeyRef.value = record.key;
  record.onEdit?.(true);
};

const handleSave = async (record) => {
  currentEditKeyRef.value = '';
  const valid = await record.onValid?.();

  const deviceCustomDataValDTOList = dateList.value
    .map((dateStr, index) => {
      const key = String(index);
      const exists = record.hasOwnProperty(key);
      const value = exists ? record[key] : 0;
      return value !== 0 ? {
        date: dateStr,
        dailyConsumption: value,
        remark: '',
        currentStorageLevel: record.currentStorageLevel || 0
      } : null;
    })
    .filter(item => item !== null);
  const remarkValue = record.remark || '';

  if (deviceCustomDataValDTOList.length > 0) {
    deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].remark = remarkValue;
    deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].totalStock = deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].dailyConsumption;
  }

  const data = {
    classifyId: record.type,
    data: deviceCustomDataValDTOList,
  };
  await cssConsumptionAddOrUpdate(data);
  console.log(data);

  const pass = await record.onEdit?.(false, true);
  msg.success({ content: '数据已保存', key: 'saving' });
  handleCancel(record);
  handleSaveAndNotifyChild()
  getTypeList();
};

const formatEditedData = (editedData, deviceCustomDataVal) => {
  const rowData = cloneDeep(deviceCustomDataVal);
  for (const key in editedData) {
    const [, subKey, field] = key.split(',');

    if (rowData[subKey]) {
      if (editedData[key] === null) {
        if (rowData[subKey].measureTime) {
          rowData[subKey][field] = 0;
        } else {
          delete rowData[subKey];
        }
      } else {
        rowData[subKey] = {
          ...rowData[subKey],
          [field]: editedData[key],
          measureTime: subKey,
        };
      }
    }
  }

  return Object.values(rowData);
};

onMounted(async () => {
  searchRef.value.handleSearch();
  getTypeList();
});

// 处理搜索事件，更新 searchInfo 并触发查询
const handleSearch = (params) => {
  if (params) {
    Object.assign(searchInfo, params);
  }
  getData();
  nextTick(() => {
    if (currentModel.value != 'table') {
      csssGasChartsRef.value.getData(searchInfo, classifyIdsObj.value)
    }
  })
  // handleSaveAndNotifyChild()
};

watch(
  () => dateMonthValue.value,
  (readyVal) => {
    getData();
  },
);

const formatHeader = (headerData) => {
  dateList.value = headerData;
  const headerList = [
    {
      title: '化学品名称 ',
      dataIndex: 'chemicalName',
      width: 150,
      fixed: 'left',
    },
    {
      title: '物料号',
      dataIndex: 'materialNumber',
      width: 100,
      fixed: 'right',
    },
  ];

  headerData.forEach((item, index) => {
    headerList.push({
      title: `${dayjs(item).format('MM/DD')}`,
      dataIndex: index.toString(),
      width: 100,
      editRow: true,
      customRender: ({ text }) => {
        if (typeof text === 'number') {
          return text;
        } else {
          return text || '--';
        }
      },
    });
  });

  headerList.push(

    {
      title: '当前储罐液位',
      dataIndex: 'currentStorageLevel',
      width: 100,
      // fixed: 'right',
      merge: true,
    },

    {
      title: 'CCSS桶装存量',
      dataIndex: 'ccssBarrelStock',
      width: 100,
      // fixed: 'right',
      merge: true,
    },
    {
      title: '最近七天平均使用量',
      dataIndex: 'avgUsageLast7Days',
      width: 120,
      // fixed: 'right',
      merge: true,
    },
    {
      title: '预计可使用天数',
      dataIndex: 'estimatedUsageDays',
      width: 100,
      // fixed: 'right',
      merge: true,
    },
    {
      title: '储存罐最大容量',
      dataIndex: 'maximumCapacity',
      width: 100,
      // fixed: 'right',
      merge: true,
    },
    {
      title: '保底液位',
      dataIndex: 'minimumLiquidLevel',
      width: 80,
      // fixed: 'right',
      merge: true,
    }
  );

  setColumns(headerList);
};

const formatTableData = (tableData) => {
  const data = tableData.map((item) => {
    const { data: itemData, ...others } = item;
    const record = reactive({ ...others });
    itemData.forEach((value, index) => {
      record[index] = value;
    });
    // 设置 currentStorageLevel 的值为最后一个日期对应的值
    const lastDateIndex = dateList.value.length - 1;
    record.currentStorageLevel = itemData[lastDateIndex] || 0;

    // 设置 currentStorageLevel 的值为最后一个日期对应的值
    const lastDateIndex2 = dateList.value.length - 1;
    record.ccssBarrelStock = itemData[lastDateIndex2] || 0;
    return record;
  });

  setTableData(data);
};

const changeTabData = (itemName) => {
  let itemCode
  tabData.value.forEach((item) => {
    // item, itemName
    if (item.itemName == itemName) {
      itemCode = item.itemCode
    }
  });

  if (currentTab.value != 'CCSS用量图') {
    currentBtn.value = currentTab.value;
    classifyId.value = itemCode;
    getData();
  }
};

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode);
  tabData.value = [
    ...res,
    // { itemCode: chart, itemName: 'CCSS用量图' },
  ];
  classifyId.value = res[0].itemCode;
  classifyIdsObj.value.ccssClassifyIds = res
  getData();
};

const getData = () => {

  if (classifyId.value != '') {
    setLoading(true);
    selectCcssConsumptionData({
      startDay: searchInfo.startDay,
      endDay: searchInfo.endDay,
      queryType: searchInfo.queryType,
      classifyId: classifyId.value,
    })
      .then((e) => {
        formatHeader(e.xaxisList);
        formatTableData(e.yaxisList);
      })
      .catch((e) => {
        console.error('数据获取出错:', e);
      })
      .finally(() => {
        setLoading(false);
      });
  }

};

watch(
  () => searchInfo,
  (newValue) => {
    if (Object.values(newValue).length > 0 && classifyId.value) {
      getData();
    }
  },
  { immediate: true },
);

// 父组件保存并通知子组件重新加载数据
const handleSaveAndNotifyChild = async () => {
  // 这里可以添加父组件的保存逻辑
  // 模拟保存成功
  // 触发子组件的重新加载数据事件
  if (childRef.value) {
    childRef.value.reloadData();
  }
};

// 子组件重新加载数据的方法
const childReloadData = () => {
  if (childRef.value) {
    childRef.value.reloadData();
  }
};

const handleChange = (val) => {
  console.log(val)
  currentModel.value = val
}
const typeLoaded = (val) => {
  classifyIdsObj.value.gasClassifyIds = val
}
watch(() => [classifyIdsObj.value, currentModel.value], (val) => {
  console.log(3333)
  if (classifyIdsObj.value.gasClassifyIds.length && classifyIdsObj.value.ccssClassifyIds.length && currentModel.value != 'table') {
    nextTick(() => {
      csssGasChartsRef.value.getData(searchInfo, classifyIdsObj.value)
    })
  }
},{
  deep: true
})
</script>

<style scoped lang="scss">
.subitem-box {
  .subitem-btn {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(208 212 223 / 100%);
    border-radius: 2px;
    background: #f3f7fb;
    box-shadow: none;
    color: #181818;
    font-size: 12px;
    font-weight: 400;
  }

  .subitem-btn-focus {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(0 103 204 / 100%);
    border-radius: 2px;
    background: rgb(0 103 204 / 15%);
    box-shadow: none;
    color: #0067cc;
  }

  .ant-space {
    margin-bottom: 0 ! important;
  }
}

.content-box2 {
  display: flex;
  flex-direction: column;
  padding: 0 8px;
  background: #fff;
}

.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #fff;
  overflow: hidden;


  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}

/* 新增样式：设置表格和底部组件各占50%高度 */
.main-box {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;
}

.content-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.table-container,
.bottom-container {
  flex: 1;
  min-height: 0;
  /* 确保在内容过多时可以滚动 */
  padding: 8px;
  box-sizing: border-box;
  overflow: hidden;
}

.table-container {
  border-bottom: 1px solid #e8e8e8;
  :deep(.ant-card-body){
    flex: 1;
    overflow: hidden;
  }
}

/* 调整表格卡片的高度，使其充满容器 */
.common-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.common-card .ant-card-body {
  flex: 1;
  padding: 16px 0;
  display: flex;
}

.common-card .ant-card-body>div {
  flex: 1;
}
</style>